<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2020/4/21
 * Time: 16:08
 */

namespace app\admin\controller;

use think\Db;
use think\Request;

class Hot extends Base
{
    /**
     * 热门搜索词列表
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax ()){
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::name('hot')->count();// 获取总条数
            $lists = Db::name('hot')
                ->field('hot_id, hot_word, hot_time')
                ->page($Nowpage,$limits)
                ->order('hot_time desc')
                ->select();
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch();
    }
    
    /**
     * 添加热门搜索词
     * @return mixed|\think\response\Json
     */
    public function hotAdd(){
        if(Request::instance()->isPost()){
            $insert = [
                'hot_word' => trim(input('hot_word'), ' '),
                'hot_time' => date('Y-m-d H:i:s')
            ];
            $res = Db::table('up_hot')->insert($insert);
            if($res){
                return json(['code' => 200, 'msg' => '添加成功']);
            }else{
                return json(['code' => 100, 'msg' => '添加失败']);
            }
        }
        return $this->fetch('hot/hotadd');
    }
    
    /**
     * 编辑热门搜索词
     * @return mixed|\think\response\Json
     */
    public function hotEdit(){
        $hot_id = input('hot_id');
        if(Request::instance()->isPost()){
            $res = Db::table('up_hot')
                ->where('hot_id', $hot_id)
                ->update(['hot_word' => trim(input('hot_word'), ' ')]);
            if($res){
                return json(['code' => 200, 'msg' => '编辑成功']);
            }else{
                return json(['code' => 100, 'msg' => '编辑失败']);
            }
        }
        $word = Db::table('up_hot')->where('hot_id', $hot_id)->value('hot_word');
        $this->assign([
            'word' => $word,
            'hot_id' => $hot_id
        ]);
        return $this->fetch('hot/hotedit');
    }
    
    /**
     * 删除热门搜索词
     * @return \think\response\Json
     */
    public function hotDel(){
        $hot_id = input('id');
        $res = Db::table('up_hot')->delete($hot_id);
        if($res){
            return json(['code' => 200, 'msg' => '删除成功']);
        }else{
            return json(['code' => 100, 'msg' => '删除失败']);
        }
    }
}